from flask import Flask, jsonify,request, render_template
import win32print,win32api
import requests
import os
from docxtpl import DocxTemplate
from flask_cors import CORS
app = Flask(__name__)
CORS(app)

# 获取所有可用打印机
def get_printers():
    printers = []

    for i,printer in enumerate(win32print.EnumPrinters(6)):
        printers.append({'value':i,'text':printer[2]})

    return printers
def print_now(printer,pdf_path):
    win32print.SetDefaultPrinter(printer)

    try:
        win32api.ShellExecute(
            0,
            "print",
            pdf_path,
            '/d:"%s"' % win32print.GetDefaultPrinter(),
            ".",
            0
        )
        return {'success': True, 'msg':'打印成功'}
    except Exception as e:
        print(e)
        return  {'success':False,'msg':e}
def download_file(origin,reportSrc,filename):
    url=''.join([origin,reportSrc])
    if not os.path.isdir(os.path.join(os.path.dirname(os.path.abspath(__file__)),'temp')):
        os.makedirs(os.path.join(os.path.dirname(os.path.abspath(__file__)),'temp'),exist_ok=True)
    local_filename=os.path.join(os.path.dirname(os.path.abspath(__file__)),'temp',filename)
    # 发送 GET 请求
    with requests.get(url, stream=True) as response:
        response.raise_for_status()  # 检查请求是否成功
        # 打开本地文件以写入二进制数据
        with open(local_filename, 'wb') as f:
            # 分块写入文件
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
    return local_filename

@app.route('/print', methods=['OPTIONS', 'POST', 'GET'])
def upload_file():
    if request.method == 'OPTIONS':
        response = jsonify({'message': 'CORS preflight response'})
        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Methods', 'POST, OPTIONS, GET')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
        return response

    if request.method == 'POST':
        #发送者路由
        origin=request.origin
        items=request.json.get('items')
        reportSrc=request.json.get('report').get('href')
        filename=request.json.get('report').get('data_label')
        local_file_path=download_file(origin,reportSrc,filename)
        printer=request.json.get('printer')
        type=request.json.get('printType') #打印类型
        print(printer,local_file_path)
        file_name, file_extension = os.path.splitext(local_file_path)
        if 'pdf' in file_extension:
            if type=='print':
                print_now(printer, local_file_path)
            elif type=='printPreview':
                os.startfile(local_file_path)  # 加载打印模板 # 打印预览
        elif 'docx' in file_extension:

            tpl1 = DocxTemplate(local_file_path)
            out_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),'temp','123'+filename)
            # doc.SaveAs(outputFile, FileFormat=17)  # 转成pdf
            obj= {'shu': 3}
            # obj = self.print_get_data(text)
            tpl1.render(obj)
            tpl1.save(out_path)
        return {'msg': '打印成功'}
    if request.method == 'GET':
        return {'printers': get_printers()}


@app.route('/connect')
def connect():
    return '连接成功'





if __name__ == '__main__':
    # 确保上传目录存在
    # get_printers()
    app.run(debug=True,  port=5003)